package com.lxq.live;

import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.junit.jupiter.api.Test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

public class CaptureVideo {
    public static Long getVideoTime(File file) {
        long times = 0L;
        try {
            FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
            ff.start();
            times = ff.getLengthInTime() / (1000 * 1000);
            ff.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return times;
    }

    static void fetchPic(File file, String frameFile) throws Exception {
        FFmpegFrameGrabber ff = new FFmpegFrameGrabber(file);
        ff.start();
        int length = ff.getLengthInFrames();
        File targetFile = new File(frameFile);
        int i = 0;
        Frame frame = null;
        while (i < length) {
            frame = ff.grabImage();
            if ((i > 8125) && (frame.image != null)) {
                break;
            }
            i++;
        }

        Java2DFrameConverter converter = new Java2DFrameConverter();
        BufferedImage srcBi = converter.getBufferedImage(frame);
        try {
            ImageIO.write(srcBi, frameFile.substring(frameFile.lastIndexOf(".") + 1), targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ff.stop();
    }

    @Test
    void mkrRepository() {
        var virtualPublic = new File("D:/live_repository/public/");
        if (!virtualPublic.exists()) System.out.println("public:" + virtualPublic.mkdirs());
        var virtualUser = new File("D:/live_repository/user_zone/");
        if (!virtualUser.exists()) System.out.println("user_zone:" + virtualUser.mkdirs());
    }


    @Test
    void test() throws Exception {
        String filePath = "D:/live_repository/public/videouuid/澜.mp4";
        fetchPic(new File(filePath), "D:/live_repository/public/videouuid/澜.jpg");
    }
}
